package sichuan.ytf.thread;

import java.io.IOException;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Future;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * 线程池等待一段时间后，停止线程
 * 
 * @author taifu
 *
 */
public class ExecutorServiceFutureTest {

    public static void main(String[] args) throws IOException, InterruptedException {
        // 创建一个固定大小的线程池
//        ExecutorService service = Executors.newFixedThreadPool(3);
        ExecutorService service = new ThreadPoolExecutor(50, 50, 0L, TimeUnit.MILLISECONDS,
                new LinkedBlockingQueue<Runnable>(500));

        List<Future<?>> list = new ArrayList<>();
        for (int i = 0; i < 10; i++) {
            System.out.println("创建线程" + i);
            int j = i;
            Runnable run = new Runnable() {
                @Override
                public void run() {
                    try {
                        if (j == 1)
                            Thread.sleep(2000);
                        System.out.println("执行线程" + j);
                    } catch (InterruptedException e) {
                        System.out.println("【异常】被打断的异常2");
                    } catch (Exception e) {
                        System.out.println(e.getMessage());
                    }
                }
            };
            // 在未来某个时间执行给定的命令
            list.add(service.submit(run));
        }
        try {
            service.awaitTermination(1000, TimeUnit.MILLISECONDS);
            System.out.println("等待1s结束");
            for (Future<?> future : list) {
                if (!future.isDone())
                    future.cancel(true);
            }
        } catch (InterruptedException e) {
            System.out.println("【异常】被打断的异常");
        }
        System.out.println("all thread complete ");

    }
}